package org.ikastola

import ikastola.Constants;
import java.util.Date;
import org.springframework.dao.DataIntegrityViolationException
import org.springframework.transaction.annotation.Transactional;
import grails.plugins.springsecurity.Secured

@Secured(['ROLE_ADMIN'])
class StudentController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index() {
        redirect(action: "list", params: params)
    }

    def list(Integer max) {
        params.max = Math.min(max ?: 10, 100)
        [studentInstanceList: Student.findAllByDeleted(Constants.NOT_DELETED, params), studentInstanceTotal: Student.countByDeleted(Constants.NOT_DELETED)]
    }

    def create() {
        [studentInstance: new Student(params)]
    }

	@Transactional
    def save() {
       
		def serviceInstance = new Service(fees: params.fees, discounts: params.disc)
		serviceInstance.setClassCreated(new Date())
		serviceInstance.setDeleted(Constants.NOT_DELETED)
		
		def studentInstance = new Student(params)
		studentInstance.setService(serviceInstance)
		studentInstance.setDeleted(Constants.NOT_DELETED)
		studentInstance.setClassCreated(new Date())
						
        if (!serviceInstance.save(flush: true) || !studentInstance.save(flush: true)) {
            render(view: "create", model: [studentInstance: studentInstance])
            return
        }

        flash.message = message(code: 'default.created.message', args: [message(code: 'student.label', default: 'Student'), studentInstance.id])
        redirect(action: "show", id: studentInstance.id)
    }

    def show(Long id) {
        def studentInstance = Student.get(id)
        if (!studentInstance || Constants.DELETED.equals(studentInstance.getDeleted())) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'student.label', default: 'Student'), id])
            redirect(action: "list")
            return
        }

        [studentInstance: studentInstance]
    }

    def edit(Long id) {
        def studentInstance = Student.get(id)
        if (!studentInstance || Constants.DELETED.equals(studentInstance.getDeleted())) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'student.label', default: 'Student'), id])
            redirect(action: "list")
            return
        }

        [studentInstance: studentInstance]
    }

	@Transactional
    def update(Long id, Long version) {
        def studentInstance = Student.get(id)
        if (!studentInstance || Constants.DELETED.equals(studentInstance.getDeleted())) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'student.label', default: 'Student'), id])
            redirect(action: "list")
            return
        }

        if (version != null) {
            if (studentInstance.version > version) {
                studentInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                          [message(code: 'student.label', default: 'Student')] as Object[],
                          "Another user has updated this Student while you were editing")
                render(view: "edit", model: [studentInstance: studentInstance])
                return
            }
        }

		def serviceInstance = studentInstance.getService()
		if (!serviceInstance || Constants.DELETED.equals(serviceInstance.getDeleted())) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'service.label', default: 'Service'), id])
			redirect(action: "list")
			return
		}
		
		Set feeList = []
		for (i in params.fees) {
			feeList.add(Fee.get(i));
		}
		Set discList = []
		for (i in params.disc) {
			discList.add(Discount.get(i));
		}
			
        studentInstance.properties = params
		studentInstance.service.fees = feeList
		studentInstance.service.discounts = discList
		studentInstance.setClassUpdated(new Date())
		
        if (!studentInstance.save(flush: true)) {
            render(view: "edit", model: [studentInstance: studentInstance])
            return
        }

        flash.message = message(code: 'default.updated.message', args: [message(code: 'student.label', default: 'Student'), studentInstance.id])
        redirect(action: "show", id: studentInstance.id)
    }

	@Transactional
    def delete(Long id) {
        def studentInstance = Student.get(id)
        if (!studentInstance || Constants.DELETED.equals(studentInstance.getDeleted())) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'student.label', default: 'Student'), id])
            redirect(action: "list")
            return
        }

		def relative = Student.findAllByRelatives(studentInstance)
		if (relative) {
			flash.message = "El alumno no puede ser eliminado dado que est&aacute; indicado como hermano de otro alumno."
			redirect(action: "list")
			return
		}
		
        try {
			//baja de servicio
			def serviceInstance = studentInstance.getService()
			serviceInstance.setDeleted(Constants.DELETED)
			serviceInstance.setClassUpdated(new Date())
			serviceInstance.save(flush: true)
			//baja de alumno
			studentInstance.setDeleted(Constants.DELETED)
			studentInstance.setClassUpdated(new Date())
			studentInstance.save(flush: true)
            
			flash.message = message(code: 'default.deleted.message', args: [message(code: 'student.label', default: 'Student'), id])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e) {
            flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'student.label', default: 'Student'), id])
            redirect(action: "show", id: id)
        }
    }
	
	def search() {
		//params.max = Math.min(max ?: 10, 100)
		//System.out.println(params)
		def studentInstanceList = Student.findAllByNameIlikeAndDeleted('%'+params.query+'%',Constants.NOT_DELETED)
		if(!studentInstanceList) {
			studentInstanceList = Student.findAllByLastnameIlikeAndDeleted('%'+params.query+'%',Constants.NOT_DELETED)
		}
		if(!studentInstanceList) {
			studentInstanceList = []
		} 
		render(view: 'list', model: [studentInstanceList: studentInstanceList, studentInstanceTotal: studentInstanceList.size])
	}
	
	def listc(Integer max, Long id) {
		session.searchListc = null
		def studentInstanceList = []
		params.max = Math.min(max ?: 10, 100)
		if(id) {
			def courseInstance = Course.get(id)
			if (!courseInstance || Constants.DELETED.equals(courseInstance.getDeleted())) {
				flash.message = message(code: 'default.not.found.message', args: [message(code: 'course.label', default: 'Course'), id])
				redirect(action: "listc")
				return
			}
			studentInstanceList = Student.findAllByCourseAndDeleted(courseInstance,Constants.NOT_DELETED, params)
			session.searchListc = studentInstanceList
		}
		[studentInstanceList: studentInstanceList, studentInstanceTotal: studentInstanceList.size(), courseid: id]
//		else {
//			[studentInstanceList: Student.findAllByDeleted(Constants.NOT_DELETED, params), studentInstanceTotal: Student.countByDeleted(Constants.NOT_DELETED), courseid: id]
//		}
	}
	
	def savelistc() {
		def studentReport = Student.getAll()//service.createStudentReport(session.searchListc)
		if (!studentReport) {
			flash.message = "message"
			redirect(action: "list")
			return
		}
		params.fee = "fee"
		params.course = "course"
		params._name = "listado"
		params._file = "listcourse"
		
		chain(controller:'jasper',action:'index',model:[data:studentReport],params:params)
	}
	
//	def balances(Long id) {
//		Student st = Student.get(id)
//		System.out.println(st)
//		def balanceList = BalanceFees.findAllByStudent(st,params)
//		System.out.println(balanceList) 
//		render(view: '/balanceFees/list', ,model: [st:st, balanceFeesInstanceList: balanceList, balanceFeesInstanceTotal: balanceList.size()]) 
//	}
}
